package com.loong.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * Created by 梁浩峰 on 2016/11/24 21:42.
 */
public class ZipFileMgr {
    public static void main(String[] args) {
        //源文件路径
        String sourcePath="D:\\logs\\log";
        //输出文件路径
        String outputPath="D:\\logs\\log2.zip";

        zip(sourcePath, outputPath);
    }

    /**
     * 压缩文件或文件名
     * @param sourcePath
     * @param outputPath
     */
    private static void zip(String sourcePath, String outputPath) {
        try {
            FileOutputStream fout = new FileOutputStream(outputPath);
            //zip格式输出流
            ZipOutputStream zout = new ZipOutputStream(fout);
            //要将一个文件写到压缩输出流
            File sourcefile = new File(sourcePath);
            String zipEntryname = sourcefile.getName();
            if (sourcefile.isFile()) {
                //压缩文件
                zipFile(zout, sourcefile, zipEntryname);
            } else {
                //压缩目录
                zipDiretory(zout, sourcefile, zipEntryname);
            }

            zout.close();
            fout.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 压缩文件夹
     * @param zout
     * @param sourcefile
     * @param zipEntryname
     * @throws IOException
     */
    private static void zipDiretory(ZipOutputStream zout, File sourcefile, String zipEntryname) throws IOException {
        for (File file : sourcefile.listFiles()) {
            if (file.isFile()) {//是文件直接压缩
                zipFile(zout, file, zipEntryname+"/"+file.getName());
            } else {
                //压缩文件夹的内容
                //递归调用压缩子文件夹
                if (file.listFiles().length>0) {//快捷键ctrl+alt+T
                    zipDiretory(zout,file,zipEntryname+"/"+file.getName());
                } else {
                    zout.putNextEntry(new ZipEntry(zipEntryname+"/"+file.getName()+"/"));
                    zout.closeEntry();
                }
            }
        }
    }

    /**
     * 压缩文件
     * @param zout Zip格式输出流
     * @param sourcefile 原文件路径
     * @param zipEntryname 压缩条目
     * @throws IOException
     */
    private static void zipFile(ZipOutputStream zout, File sourcefile, String zipEntryname) throws IOException {
        zout.putNextEntry(new ZipEntry(zipEntryname));
        //读入要要压缩的文件
        FileInputStream fin = new FileInputStream(sourcefile);
        byte[] buff = new byte[1024];
        int length;
        while((length=fin.read(buff))>0){
            zout.write(buff,0,length);
        }
        fin.close();
        zout.closeEntry();
    }
}
